<template>
  <div><el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" :highlight-current="true"></el-tree></div>
</template>

<script>
import * as ProductAPI from '@/api/product.js';
import * as CategoryAPI from '@/api/category.js';
export default {
  props: {
    id: Number
  },

  data() {
    return {
      data: [], //数据结构参见官网
      defaultProps: {  // 参见官网文档
        children: 'children',
        label: 'label'
      }
    };
  },
  created() {
    this.initData();
  },

  methods: {
    async initData() {
      console.log('initData()....');
      // 获取分类信息数据，
      let result = await CategoryAPI.getCategoryList();
      let categoryList = result.data;
      // 生成树形控件的属性data数据，数据结构见官网
      for (let i = 0; i < categoryList.length; i++) {
        let category = { id: categoryList[i].id, label: categoryList[i].name };
        result = await ProductAPI.getProductList({ category_id: category.id, pageSize: 10000000 });
        let productList = result.data;
        let children = [];
        productList.forEach(item => {
          children.push({ id: item.id, label: item.id + '-' + item.title });
        });
        category.children = children;
        this.data.push(category);
      }
    },
    handleNodeClick(data, node) {
      if (node && node.level == 2) {
        //与自定义属性:id.sync对应的事件触发
        this.$emit('update:id', data.id);
      }
    }
  }
};
</script>

<style></style>
